﻿namespace EyeOpen.Wpf.MultiImage
{
	using System;
	using System.Collections.Generic;
	using System.Drawing;
	using System.Drawing.Drawing2D;
	using System.Windows;
	using System.Windows.Interop;
	using System.Windows.Media;
	using System.Windows.Media.Imaging;
	using Color = System.Drawing.Color;
	using Pen = System.Drawing.Pen;

	internal class ImageGenerator
	{
		public IEnumerable<ImageSource> GetImageList()
		{
			var imageList = new List<ImageSource>();
			const int Size = 50;

			var random = new Random();

			Func<int> nextCoordinate = () => random.Next(Size);
			Func<int> nextColor = () => random.Next(255);

			for (var i = 0; i < 10; i++)
			{
				var bitmap = CreateImage(Size, nextColor, nextCoordinate);
				var bitmapImage = GetBitmapSource(bitmap);

				imageList.Add(bitmapImage);
			}

			return imageList;
		}

		private BitmapSource GetBitmapSource(Bitmap image)
		{
			var bitmap = image;
			var bitmapSource = 
				Imaging
					.CreateBitmapSourceFromHBitmap(
						bitmap.GetHbitmap(),
						IntPtr.Zero,
						Int32Rect.Empty,
						System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
			
			return bitmapSource;
		}

		private Bitmap CreateImage(int size, Func<int> nextColor, Func<int> nextCoordinate)
		{
			var bitmap = new Bitmap(size, size);

			using (var graphics = Graphics.FromImage(bitmap))
			{
				graphics.Clear(Color.White);
				graphics.SmoothingMode = SmoothingMode.AntiAlias;
				graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

				var pen = new Pen(Color.FromArgb(nextColor(), nextColor(), nextColor()));

				graphics.DrawLine(pen, nextCoordinate(), nextCoordinate(), nextCoordinate(), nextCoordinate());
			}

			return bitmap;
		}
	}
}